/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-10-01
 * Time: 11:18
 */
//练习
//模拟阻塞队列，实现生产者消费者模型。
class MyBlockingQueue {
    private String[] items = new String[1000];
    volatile private int head = 0;
    volatile private int hail = 0;
    volatile private int size = 0;
    private Object locker = new Object();
    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while(size >= items.length) {
                System.out.println("队列满，阻塞等待！！");
                locker.wait();
            }
            items[hail] = elem;
            hail ++;
            if(hail >= items.length) {
                hail = 0;
            }
            size ++;
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (locker) {
            while (size == 0) {
                System.out.println("队列空，阻塞等待！！");
                locker.wait();
            }
            String elem = items[head];
            head ++;
            if(head >= items.length) {
                head = 0;
            }
            size --;
            locker.notify();
            return elem;
        }
    }

}
public class Demo1 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();

        //生产元素
        Thread t1 = new Thread(() -> {
            int count = 0;
            while (true) {
                try {
                    queue.put(count + "");
                    System.out.println("生产元素" + count);
                    count++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //消费元素
        Thread t2 = new Thread(()-> {
            while (true) {
                try {
                    String elem = queue.take();
                    System.out.println("消费元素" + elem);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }

}
